package com.example.common.aop;

import com.example.common.exception.CustomException;
import com.example.common.utils.RedisUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.ProceedingJoinPoint;
import java.util.concurrent.TimeUnit;

@Aspect
@Component
public class RateLimitAspect {
    
    @Autowired
    private RedisUtil redisUtil;
    
    @Around("@annotation(rateLimit)")
    public Object rateLimiter(ProceedingJoinPoint joinPoint, RateLimit rateLimit) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ip = request.getRemoteAddr();
        String uri = request.getRequestURI();
        String key = "rl:" + ip + ":" + uri;
        
        Long count = redisUtil.incr(key, 1);
        if (count == 1) {
            redisUtil.set(key, "1", rateLimit.timeWindow(), TimeUnit.SECONDS);
        }
        
        if (count > rateLimit.maxRequests()) {
            throw new CustomException(429, "请求过于频繁，请稍后再试");
        }
        
        return joinPoint.proceed();
    }
}

